package cn.tedu.weibo02.controller;

import cn.tedu.weibo02.mapper.UserMapper;
import cn.tedu.weibo02.pojo.dto.UserLoginDTO;
import cn.tedu.weibo02.pojo.dto.UserRegDTO;
import cn.tedu.weibo02.pojo.entity.User;
import cn.tedu.weibo02.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){

        UserVO userVO = mapper.selectByUsername(userRegDTO.getUsername());
        if (userVO!=null){
            return 2;
        }
        User u = new User();
        BeanUtils.copyProperties(userRegDTO,u);
        u.setCreated(new Date());
        mapper.insert(u);
        return 1;
    }
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){

       UserVO userVO = mapper.selectByUsername(userLoginDTO.getUsername());
       if (userVO!=null){
           if (userVO.getPassword().equals(userLoginDTO.getPassword())){
               session.setAttribute("user",userVO);
               return 1;
           }
           return 2;
       }
        return 3;
    }
    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
